package at.horario.web.pages;

import at.horario.model.Celula;
import at.horario.model.Horario;
import at.horario.service.CelulaManager;
import at.horario.web.property.editor.ProfessorRowModel;
import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.model.IModel;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class ProfessorRowDataProvider implements IDataProvider {
    private CelulaManager celulaManager;
    private Horario horario;

    public ProfessorRowDataProvider(Horario horario, CelulaManager celulaManager) {
        this.celulaManager = celulaManager;
        this.horario = horario;
    }

    public Iterator iterator(int first, int count) {
        List<Celula> celulas = celulaManager.getCelulas(horario, first, count);

        ProfessorRow[] professorRows = new ProfessorRow[count];
        int[] ordem = new int[count];
        for (int i = 0; i < professorRows.length; i++) {
            professorRows[i] = new ProfessorRow(horario, i + 1);
        }
        for (int i = 0; i < celulas.size(); i++) {
            Celula cel = celulas.get(i);
            int index = cel.getProfessor().getNumHorario() - first - 1;
            ProfessorRow pr = professorRows[index];
            pr.getHorarios()[cel.getNumeroHorario() - 1] = cel.getTurma();
            if (ordem[index] == 0) {
                ordem[index] = cel.getProfessor().getDisciplina().getOrdem() * 1000 + cel.getProfessor().getNumDisciplina();
                pr.setOrdem(ordem[index]);
            }
        }

        Arrays.sort(professorRows, new Comparator<ProfessorRow>() {
            public int compare(ProfessorRow o1, ProfessorRow o2) {
                return o1.getOrdem() - o2.getOrdem();
            }
        });
        return Arrays.asList(professorRows).iterator();
    }

    public int size() {
        return celulaManager.countProfessores(horario);
    }

    public IModel model(Object object) {
        return new ProfessorRowModel((ProfessorRow) object, celulaManager);
    }

    public void detach() {
    }
}
